import 'package:flutter/material.dart';

/// 缩放动画
/// END
class ScaleAnimatedContent extends StatefulWidget {
  final Widget child;
  final bool show;
  final int duration; // 动画时长
  final Function? callback; // 动画方向执行结束时回调函数

  const ScaleAnimatedContent({
    Key? key,
    required this.child,
    this.show = false,
    this.duration = 300,
    this.callback,
  }) : super(key: key);

  @override
  ScaleAnimatedContentState createState() => ScaleAnimatedContentState();
}

class ScaleAnimatedContentState extends State<ScaleAnimatedContent>
    with TickerProviderStateMixin {
  late AnimationController animationController;
  late Animation<double> animation;

  @override
  void initState() {
    animationController = new AnimationController(
      vsync: this,
      duration: Duration(milliseconds: widget.duration),
    );
    animation = Tween(begin: 0.4, end: 1.0)
        .chain(CurveTween(curve: Curves.easeInBack))
        .animate(animationController);
    if (widget.show) {
      animationController.forward();
    }
    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // 动画从forward正向执行结束时

      } else if (status == AnimationStatus.dismissed) {
        // 动画从reverse反向执行结束时
        widget.callback?.call();
      }
    });
    super.initState();
  }

  @override
  void didUpdateWidget(ScaleAnimatedContent oldWidget) {
    if (widget != oldWidget) {
      if (widget.show && !oldWidget.show) {
        animationController.forward(from: 0.4);
      } else if (!widget.show) {
        animationController.reverse();
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return ScaleTransition(
      scale: animation,
      child: widget.child,
    );
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}
